package com.gem.netty.session;

import io.netty.channel.Channel;

import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionMemoryImpl implements Session {

    private final Map<String, Channel> usernameChannelMap = new ConcurrentHashMap<>();
    private final Map<Channel, String> channelUsernameMap = new ConcurrentHashMap<>();
    private final Map<Channel,Map<String,Object>> channelAttributesMap = new ConcurrentHashMap<>();
    @Override
    public void bind(Channel channel, String username) {
        usernameChannelMap.put(username, channel);
        if (!channelUsernameMap.containsValue(username)){
            channelUsernameMap.put(channel, username);
            channelAttributesMap.put(channel, new ConcurrentHashMap<>());
        }

    }

    @Override
    public void unbind(Channel channel) {
        String username = channelUsernameMap.remove(channel);
        if(username!=null){
            usernameChannelMap.remove(username);
            channelAttributesMap.remove(channel);
        }
    }

    @Override
    public Object getAttribute(Channel channel, String name) {
        return channelAttributesMap.get(channel).get(name);
    }

    @Override
    public void setAttribute(Channel channel, String name, Object value) {
        channelAttributesMap.get(channel).put(name, value);
    }

    @Override
    public Channel getChannel(String username) {
        return usernameChannelMap.get(username);
    }

    @Override
    public Integer count() {
        return usernameChannelMap.size();
    }

    @Override
    public String getUser(Channel channel) {
        return channelUsernameMap.get(channel);
    }

    @Override
    public String toString() {
        return usernameChannelMap.toString();
    }

}
